namespace Bootsy.Jira

import System
import Bootsy.Jira.RPC

class JiraService(IJiraService):
	
	private static final AuthCookieKey = object()
	private static final ResolutionsKey = object()
	private static final TopTicketsKey = object()
	
	[getter(SoapService)]
	private final _jira = JiraSoapServiceService()
	
	private final _cache = ConcurrentBoo.ComputationCache()
	
	private final _configuration as IJiraServiceConfiguration
	
	def constructor([required] configuration as IJiraServiceConfiguration):
		_configuration = configuration
	
	def SearchIssues(terms as string):
		return _jira.getIssuesFromTextSearch(GetAuthCookie(), terms)
		
	def GetProgressReport():
		return GetIssuesFromFilter("10221")
		
	def GetTop(count as int):
		return array(issue.Value as RemoteIssue for issue in GetTop_(count))
		
	def GetTop_(count as int):
		return array(GetIssue_(ticket) for ticket in GetTopTickets()[:count])
		
	def GetIssue(ticket as string) as RemoteIssue:
		return GetIssue_(ticket).Value
		
	def GetIssuesFromFilter(filterId as string) as (RemoteIssue):
		return GetIssuesFromFilter_(filterId).Value
		
	def GetIssuesFromFilter_(filterId as string):
		return _cache.Get(filterId, { _jira.getIssuesFromFilter(GetAuthCookie(), filterId) })
		
	def GetIssue_(ticket as string):
		return _cache.Get(ticket, { _jira.getIssue(GetAuthCookie(), ticket) })
		 
	def GetResolutionName(id as string):
		if id is null: return "Open"
		resolution = GetResolution(id)
		if resolution is null: return "Open"
		return resolution.name
			
	def GetResolution(id as string):
		for r in GetResolutions():
			if r.id == id: return r

	def GetResolutions() as (RemoteResolution):
		return GetResolutions_().Value
		
	def GetResolutions_():
		return _cache.Get(ResolutionsKey, { _jira.getResolutions(GetAuthCookie()) })
				
	def GetAuthCookie() as string:
		return GetAuthCookie_().Value
		
	def GetAuthCookie_():
		return _cache.Get(AuthCookieKey, { _jira.login(_configuration.Login, _configuration.Password) })
		
	def GetSavedFilters():
		return _jira.getSavedFilters(GetAuthCookie())

	def GetTopTickets() as (string):
		return GetTopTickets_().Value
		
	def GetTopTickets_():
		return _cache.Get(TopTicketsKey, FetchTopTickets)
		
	def FetchTopTickets():
		return array(ticket for ticket in FetchTopTickets_())
		
	private def FetchTopTickets_():
		page = HtmlAgilityPack.HtmlWeb().Load("http://tracker.db4o.com/browse/COR?report=com.atlassian.jira.plugin.system.project:popularissues-panel")
		topRows = page.CreateNavigator().Select("//div[@class='header']/h3[text()='Popular Issues']/../../table/tr")
		for topRow as HtmlAgilityPack.HtmlNodeNavigator in topRows:
			link as HtmlAgilityPack.HtmlNodeNavigator, = topRow.Select("td[6]/a")
			href = link.CurrentNode.GetAttributeValue("href", "")
			// href should look like '/browse/COR-36'
			yield href.Split(char('/'))[-1]

